<?php

if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Appmodel extends CI_Model {

	protected $_CI;

	public static $searchField = array();
	public static $likeField = array();

	public function __construct(){
		parent::__construct();
		$this->_CI = & get_instance();
	}

/*
| -------------------------------------------------------------------
|  Customer Functions
| -------------------------------------------------------------------
*/
	public function checkCustomerLogin(){
		$customer = $this->session->userdata('customer');

		if($customer === false) return false;
		if(!is_array($customer)) return false;
		if(empty($customer)) return false;
		if(!isset($customer['customer_id'])) return false;

		return true;
	}

	public function getCurrentCustomerId(){
		if($this->checkCustomerLogin()){
			$customer = $this->session->userdata('customer');
			return $customer['customer_id'];
		}else{
			return 0;
		}
	}

	public function getCurrentCustomerName(){
		if($this->checkCustomerLogin()){
			$customer = $this->session->userdata('customer');
			return $customer['customer_name'];
		}else{
			return '';
		}
	}
	
/*
| -------------------------------------------------------------------
|  User Functions
| -------------------------------------------------------------------
*/
	public function getAllActions() {
		global $g_menu;
		$menu = $g_menu;
		$menu = $this->_array_remove_empty($menu);
		$action_list = array();
		foreach ($menu as $k0 => $v0) {
			foreach ($v0 as $k1 => $v1) {
				foreach ($v1 as $k2 => $ctrller) {
					if(!class_exists($ctrller)&&file_exists(APPPATH.'controllers/admin/'.$ctrller.EXT)){
						require(APPPATH.'controllers/admin/'.$ctrller.EXT);
					}
					if(file_exists(APPPATH.'controllers/admin/'.$ctrller.EXT)){
						$class_methods = get_class_methods($ctrller);	
					}
					
 					
					foreach($class_methods as $method){
						if(!in_array($method,array('__construct','__destruct','get_instance'))){
							$action = $ctrller.'/'.$method;
							$action_list[] = $action;
						}
					}
				}
			}
		}

		return $action_list;
	}
	
	public function checkUserLogin(){
		$user = $this->session->userdata('user');
		// $ip = $this->_CI->input->ip_address();

		if($user === false) return false;
		if(!is_array($user)) return false;
		if(empty($user)) return false;
		if(!isset($user['user_name'])) return false;
		// if(!isset($user['auth_code']) || $user['auth_code'] != md5($ip.SALT) ) return false;

		return true;
	}

	public function getCurrentUserId(){
		if($this->checkUserLogin()){
			$user = $this->session->userdata('user');
			return $user['user_id'];
		}else{
			return 0;
		}
	}

	public function isRoot(){
		if($this->checkUserLogin()){
			$user = $this->session->userdata('user');
		}else{
			$user = array();
		}

		if(isset($user['user_id']) && $user['user_id'] == 1){
			return true;
		}else{
			return false;
		}
	}

	public function getMenu() {
		$menu = $this->session->userdata('menu');
		return $menu;
	}

	public function getCurrentUserActionList(){
		if($this->checkUserLogin()){
			$user = $this->session->userdata('user');
			return $user['pms_action_list'];
		}else{
			return array();
		}
	}

	public function getCurrentUserName(){
		if($this->checkUserLogin()){
			$user = $this->session->userdata('user');
			return $user['user_name'];
		}else{
			return '';
		}
	}

	public function initMenu($action=array()) {
		global $g_menu;
		$menu = $g_menu;
		$baseUrl = base_url().'admin/';

		$mnu_layout = array();

		$rebuild_menu = array();
		foreach ($menu as $k0 => &$v0) {
			$url = '';
			foreach ($v0 as $k1 => &$v1) {
				foreach ($v1 as $k2 => &$v2) {
					if(!PERMISSION_DISABLE) {
						if(in_array($v2, $action)) {
							if(empty($url)) {
								$url = $v2;
							}
							$rebuild_menu[$v2] = array($k0,$k1,$k2,$baseUrl.$url,$baseUrl.$v2);
						} else {
							unset($v1[$k2]);
						}
					} else {
						if(empty($url)) {
							$url = $v2;
						}
						$rebuild_menu[$v2] = array($k0,$k1,$k2,$baseUrl.$url,$baseUrl.$v2);
					}
				}
			}
			if(!empty($url)) {
				$mnu_layout[] = array(
					'id' => $k0,
					'url' => $baseUrl.$url,
					'text' => $k0,
				);
			}
		}

		$menu = $this->_array_remove_empty($menu);
		$rebuild_menu['base_mnu'] = $menu;
		$rebuild_menu['mnu_layout'] = $mnu_layout;
		return $rebuild_menu;
	}

	private function _array_remove_empty($haystack) {
		foreach ($haystack as $key => $value) {
			if (is_array($value)) {
				$haystack[$key] = $this->_array_remove_empty($haystack[$key]);
			}

			if (empty($haystack[$key])) {
				unset($haystack[$key]);
			}
		}

		return $haystack;
	}

/*
| -------------------------------------------------------------------
|  Permission Functions
| -------------------------------------------------------------------
*/
	public function checkUserAccess($ctrl = false,$action = false){
		if(defined('PERMISSION_DISABLE') && PERMISSION_DISABLE == true){
			return true;
		}

		$permissionArr = $this->getCurrentUserActionList();

		if($ctrl == false){
			$ctrl = $this->_defaultController();
		}
		if($action == false){
			$action = 'index';
		}

		$ctrl = strtolower($ctrl);
		$action = strtolower($action);

		$permission = false;
		global $g_common_menu;
		if(in_array($ctrl.'/'.$action,$permissionArr) || in_array($ctrl.'/'.$action,$g_common_menu)){
			$permission = true;
		}
		return $permission;
	}

	public function outputPermission($ctrl){
		$res = array();
		if(defined('PERMISSION_DISABLE') && PERMISSION_DISABLE == true){
			$class_methods = get_class_methods($ctrl);
		 
			foreach($class_methods as $method){
				if(in_array($method,array('__construct','__destruct','get_instance'))){
					continue;
				}
				$pms = $ctrl.'/'.$method;
				$pms = strtolower($pms);
				$res[$pms]=true;
			}
		}else{
			$permissionArr = $this->getCurrentUserActionList();
			foreach($permissionArr as $rec){
				list($c,) = explode('/',$rec);
				if($c == $ctrl) $res[str_replace('.','/',$rec)]=true;
			}
		}

		return json_encode($res);
	}
/*
| -------------------------------------------------------------------
|  App Private Functions
| -------------------------------------------------------------------
*/
	protected function _defaultController(){
		global $RTR;
		if(isset($RTR->routes['default_controller'])){
			$default_controller = $RTR->routes['default_controller'];
		}else{
			$default_controller = '';
		}
		
		return $default_controller;
	}
/*
| -------------------------------------------------------------------
|  INIT Functions
| -------------------------------------------------------------------
*/
	public function initFolder(){
		global $g_product_img_size_arr;
		$folder_arr = array(
			UPLOAD_PATH_ORIGIN,
			UPLOAD_PATH_THUMB,
			UPLOAD_PATH_FILE,
		);

		$old = umask(0);
		foreach($folder_arr as $folder){
			@mkdir($folder.date('Ym'),0777,true);
		}
		umask($old);

		return true;
	}

	public function saveFile($file,$config = array(),$dir = UPLOAD_PATH_ORIGIN,$name='') {
		if(!empty($config)) {
			$size = getimagesize($file['tmp_name']);
			if($size === false || !isset($size[0]) || !isset($size[1])){
				$this->response->setDetail("请上传图片");
				$this->response->responseExit();
			}
			if(!empty($config['width']) && $size[0] != $config['width']) {
				$this->response->setDetail("请上传宽为{$config['width']}的图片");
				$this->response->responseExit();
			}
			if(!empty($config['height']) && $size[1] != $config['height']) {
				$this->response->setDetail("请上传高为{$config['height']}的图片");
				$this->response->responseExit();
			}
		}
		$this->initFolder();
		$path = date('Ym').'/'.($name===true? $file['name'] : ($name ? $name : date('dHis'))).rand(10,99).'.'.pathinfo($file['name'],PATHINFO_EXTENSION);
		$image_flag = move_uploaded_file($file['tmp_name'],$dir.$path);
		if(!$image_flag || !file_exists($dir.$path)) {
			$this->response->setDetail("文件错误");
			$this->response->responseExit();
		}
		$is_to_origin = true;
		if(!empty($config)) {
			if(!empty($config['scale_width']) || !empty($config['scale_height'])) {
				$scale_dir = empty($config['scale_dir'])? UPLOAD_PATH_THUMB:$config['scale_dir'];
				$this->load->library('image');
				$this->image->loadImage($dir.$path);
				$this->image->resize(isset($config['scale_width']) ? $config['scale_width'] : 0,isset($config['scale_height']) ? $config['scale_height'] : 0);
				$this->image->save($scale_dir.$path);
				$this->image->destroy();
				if($scale_dir == UPLOAD_PATH_ORIGIN) {
					$is_to_origin = false;
				}
			}
			if(!empty($config['scale_list']) && is_array($config['scale_list'])) {
				foreach ($config['scale_list'] as $k => $v) {
					if(!empty($v['scale_width']) || !empty($v['scale_height'])) {
						$scale_dir = empty($v['scale_dir'])? UPLOAD_PATH_THUMB:$v['scale_dir'];
						$this->load->library('image');
						$this->image->loadImage($dir.$path);
						$this->image->resize(isset($v['scale_width']) ? $v['scale_width'] : 0,isset($v['scale_height']) ? $v['scale_height'] : 0);
						$this->image->save($scale_dir.$path);
						$this->image->destroy();
						if($scale_dir == UPLOAD_PATH_ORIGIN) {
							$is_to_origin = false;
						}
					}
				}
			}
		}
		// if($is_to_origin) {
		// 	copy(UPLOAD_PATH_SOURCE.$path,UPLOAD_PATH_ORIGIN.$path);
		// }
		return $path;
	}
/*
| -------------------------------------------------------------------
|  DATA Functions
| -------------------------------------------------------------------
*/
	public function getTodayData(){
		$res['time'] = NOW;

		$this->db->from('customer');
		$this->db->where('customer_date_register >=',TODAY.' 00:00:00');
		$this->db->where('customer_status',STATUS_ACTIVE);
		$res['customer_add'] = $this->db->count_all_results();

		$this->db->from('contribute');
		$this->db->where('contribute_time_record >=',TODAY.' 00:00:00');
		$this->db->where('contribute_status',STATUS_ACTIVE);
		$res['contribute_add'] = $this->db->count_all_results();

		$this->db->from('contribute');
		$this->db->where('contribute_time_record >=',TODAY.' 00:00:00');
		$this->db->where('contribute_status',STATUS_ACTIVE);
		$query = $this->db->get();
		$list = $query->result_array();

		$types = extractColumn($list,'contribute_type_id');
		$types[] = -1;
		$this->db->from('contribute_type');
		$this->db->where_in('contribute_type_id',$types);
		$query = $this->db->get();
		$types = $query->result_array();
		$types = reindexArray($types,'contribute_type_id');

		$res['resource']['contribute_tree'] = 0;
		$res['resource']['contribute_oil'] = 0;
		$res['resource']['contribute_carbon'] = 0;
		$res['contribute_type'] = array();
		foreach ($list as $record) {
			$res['resource']['contribute_tree'] += $record['contribute_tree'];
			$res['resource']['contribute_oil'] += $record['contribute_oil'];
			$res['resource']['contribute_carbon'] += $record['contribute_carbon'];
			if(isset($res['contribute_type'][$record['contribute_type_id']])){
				$res['contribute_type'][$record['contribute_type_id']]['quantity'] += $record['contribute_quantity'];
			}else{
				$res['contribute_type'][$record['contribute_type_id']]['quantity'] = $record['contribute_quantity'];
				if(isset($types[$record['contribute_type_id']])){
					$res['contribute_type'][$record['contribute_type_id']]['title'] = $types[$record['contribute_type_id']]['contribute_type_title'];
				}else{
					$res['contribute_type'][$record['contribute_type_id']]['title'] = '';
				}
			}
		}
		$res['contribute_type'] = array_values($res['contribute_type']);

		$this->db->select('sum(order_score) as order_score');
		$this->db->from('order');
		$this->db->where('order_time_create >=',TODAY.' 00:00:00');
		$query = $this->db->get();
		$res['score'] = $query->row_array();
		$res['score'] = empty($res['score']) ? 0 : intval($res['score']['order_score'])/MICSCORE_RATE;


		return $res;
	}
/*
| -------------------------------------------------------------------
|  App Extern Functions
| -------------------------------------------------------------------
*/
	public function remoteAccessLog($uri){
		$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '0.0.0.0';
		$this->db->insert('terminal_access_log',array(
			'terminal_access_log_ip' => $ip,
			'terminal_access_log_uri' => $uri,
			'terminal_access_log_time_create' => NOW,
		));
	}

}